package com.surfilter.massdata.spark.task.daystati;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.Row;
import org.apache.spark.storage.StorageLevel;

import scala.Function1;
import scala.Tuple2;

import com.act.sparkanalyz.service.impl.SparkService.OutQueueEntity;
import com.act.sparkanalyz.task.ISparkTask;
import com.surfilter.massdata.spark.bean.DnsCount;
import com.surfilter.massdata.spark.bean.IndustryDomain;
import com.surfilter.massdata.spark.bean.SA7601;
import com.surfilter.massdata.spark.util.CommonUtils;
import com.surfilter.massdata.spark.util.ConfigUtil;
import com.surfilter.massdata.spark.util.DateUtil;
import com.surfilter.massdata.spark.util.URLUtil;

public class DomainAnalyzTask_SA7601_New  implements ISparkTask{
	
	private static final Log log = LogFactory.getLog(DomainAnalyzTask_SA7601_New.class);
	private static final long serialVersionUID = 1L;

	@Override
	public List<OutQueueEntity> execute(Map<String, DataFrame> dataFrames, Map<String, String> commandMap) {
		long start=System.currentTimeMillis();
		long temp=start;
		long temp_end=start;
		double exectime=0.0;
		
		System.out.println("==============DomainAnalyzTask_SA7601 begin====================");
		List<OutQueueEntity> outList = new ArrayList<OutQueueEntity>();
		try{
			String p_linces_key = new String(ConfigUtil.get("LICENSE_KEY").getBytes("ISO-8859-1"),"UTF-8");
			log.info("LICENSE_KEY="+p_linces_key);
			DataFrame dataSource = dataFrames.get("day_domain");
		
			JavaRDD<String> domainSuffix = dataSource.toJavaRDD().map(new Function<Row,String>(){
				private static final long serialVersionUID = 1L;
				@Override
				public String call(Row row){
					String domain = row.getAs("domain");
					String topDomain = "";
					try{
						 topDomain = URLUtil.getDomainName("http://" + domain);
					}catch(Exception e){
						if(log.isErrorEnabled()){
							log.error(e.getMessage(),e);
						}
					}
					return topDomain + "@" + row.getAs("visit_count");
				}});
	        JavaPairRDD<String,Long> domainPair = domainSuffix.mapToPair(new PairFunction<String,String,Long>(){
				private static final long serialVersionUID = 1L;
				@Override
				public Tuple2<String, Long> call(String value){
					try{
						String[] valueStr = value.split("@");
						String domain = valueStr[0];
						if(StringUtils.isNotBlank(domain)){
							long count = Long.parseLong(valueStr[1]);
							
							return new Tuple2<String,Long>(domain,count);
						}
					}catch(Exception e){
						if(log.isErrorEnabled()){
							log.error(e.getMessage(),e);
						}
					}
					return new Tuple2<String,Long>("",0L);
				}});
	        JavaPairRDD<String,Long> domainCounts = domainPair.reduceByKey(new Function2<Long,Long,Long>(){
				private static final long serialVersionUID = 1L;
				@Override
				public Long call(Long x, Long y)throws Exception {
					return x+y;
				}});
	        
	        @SuppressWarnings("serial")
			JavaRDD<DnsCount> dnsRDD = domainCounts.mapPartitions(new FlatMapFunction<Iterator<Tuple2<String,Long>>,DnsCount>() {

				@Override
				public Iterable<DnsCount> call(Iterator<Tuple2<String, Long>> it){
					List<DnsCount> list = new ArrayList<DnsCount>(); 
					while(it.hasNext()){
						Tuple2<String, Long> tuple = it.next();
						String domain = tuple._1;
						if(StringUtils.isNotBlank(domain)){
							DnsCount sa = new DnsCount();
							sa.setTop_domain(domain);
							sa.setCount(tuple._2);
							list.add(sa);
						}
					}
					return list;
				}
			});
	        temp_end=System.currentTimeMillis();
            exectime=(temp_end-temp)*1.0/(1000*60);
            temp=temp_end;
			System.out.println("topdomain 合并  exectime: "+exectime+" min........................");
			
	        System.out.println("............本省接入....开始............");
	    	DataFrame df_dc = dataSource.sqlContext().createDataFrame(dnsRDD, DnsCount.class);
	        df_dc.registerTempTable("df_dc_temp");
	        df_dc.persist(StorageLevel.MEMORY_AND_DISK_SER());
			String sql = "select a.top_domain,a.count, "
					+ "(CASE WHEN ISNULL(b.license_key) = false THEN B.license_key ELSE  'N/A' END) AS license_key,"
					+ "(CASE WHEN ISNULL(b.site_name) = false THEN b.site_name ELSE  'N/A' END) AS site_name, "
					+ "(CASE WHEN ISNULL(b.PARENT_INDUSTRY_TYPE) = false THEN b.PARENT_INDUSTRY_TYPE ELSE  '221' END) AS PARENT_INDUSTRY_TYPE "
					+ "from df_dc_temp a left join br2005_temp b on a.top_domain = b.top_domain order by a.count desc "; 
			
			DataFrame oper_tmp = dataSource.sqlContext().sql(sql);
			oper_tmp.persist(StorageLevel.MEMORY_AND_DISK_SER());
			List<Row> top_domain_100 = oper_tmp.toJavaRDD().take(100);
			
	    	List<SA7601> list_SA7601 = new ArrayList<SA7601>();	
	        String dayStr = commandMap.get("-d");
	        Date date = DateUtil.getExecDate(DateUtil.getYesterday(),dayStr);
		    
	        if(top_domain_100.size() > 0){
	        	int j = 1;
	        	for(Row row_top_domain_100 : top_domain_100){
	        	    SA7601 sa = new SA7601();
	        		sa.setYear(DateUtil.getCurrentYear(date));
	        		sa.setHalf_year(DateUtil.getHalfYear(date));
	        		sa.setQuarter(DateUtil.getQuarter(date));
	        		sa.setMonth(DateUtil.getCurrentMonth(date));
	        		sa.setWeek(DateUtil.getCurrentWeek(date));
	        		sa.setDay(DateUtil.getCurrentDay(date));
	        		sa.setBuss_type("WEBSITE_RANK_SUM");
	        		sa.setBuss_value("");
	        		sa.setRank(j++);
	        		sa.setDomain(row_top_domain_100.getAs("top_domain").toString());
	        	    sa.setWebsite_name(row_top_domain_100.getAs("site_name").toString());
	        	    sa.setIcp_num(row_top_domain_100.getAs("license_key").toString());
	        	    sa.setTraffic(row_top_domain_100.getAs("count").toString());
	        		sa.setSta_range(0);
	        		list_SA7601.add(sa);
	        	}
	        	
	        }
	        temp_end=System.currentTimeMillis();
            exectime=(temp_end-temp)*1.0/(1000*60);
            temp=temp_end;
			System.out.println("本省接入  exectime: "+exectime+" min........................");
	        System.out.println("............网站分类....开始............");
			//分类网站访问量排名 --begin
	        JavaRDD<IndustryDomain> industry_RDD= oper_tmp.toJavaRDD().mapPartitions(new FlatMapFunction<Iterator<Row>, IndustryDomain>(){

				@Override
				public Iterable<IndustryDomain> call(Iterator<Row> t) throws Exception {
					List <IndustryDomain> list= new ArrayList<IndustryDomain>();
					while(t.hasNext()){
						Row row=t.next();
						IndustryDomain e=new IndustryDomain();
						e.setCount(Long.valueOf(row.getAs("count").toString()));
						e.setLicense_key(row.getAs("license_key").toString());
						e.setParent_industry_type(row.getAs("PARENT_INDUSTRY_TYPE").toString());
						e.setSite_name(row.getAs("site_name").toString());
						e.setTop_domain(row.getAs("top_domain").toString());
						list.add(e);
					}
					return list;
				}
	        	
	        });
	        
	        JavaSparkContext ctx = new JavaSparkContext(dataSource.sqlContext().sparkContext());
	    	DataFrame industry_df = dataSource.sqlContext().createDataFrame(industry_RDD, IndustryDomain.class);
	    	industry_df.registerTempTable("industry_domain");
	        String industry_sql="select top_domain,license_key,site_name,parent_industry_type,count from industry_domain order by parent_industry_type,count desc";
	        DataFrame industry_tmp_df = dataSource.sqlContext().sql(industry_sql);
	        
	        String sql_br2005_industry="select distinct parent_industry_type from br2005_temp";
	    	DataFrame industry_type_df = dataSource.sqlContext().sql(sql_br2005_industry);
	    	
	    	JavaRDD<Row> industry_tmp_RDD = industry_tmp_df.toJavaRDD();
	    	industry_tmp_RDD.persist(StorageLevel.MEMORY_AND_DISK_SER());
	        
	    	List<Row> type_list=industry_type_df.toJavaRDD().collect();
	    	for(int i=0;i<type_list.size();i++){
	    		final String type=type_list.get(i).getAs("parent_industry_type").toString();
	    		List<Row> industryDomainList=industry_tmp_RDD.filter(new Function<Row, Boolean>(){
					@Override
					public Boolean call(Row v1) throws Exception {
						String industry_type=v1.getAs("parent_industry_type").toString();
						if(StringUtils.equals(type, industry_type)){
							return true;
						}
						return false;
					}
				}).take(100);
	    		
	    		//type_list
	    		if(industryDomainList.size()>0){
	    			for(int j=0;j<industryDomainList.size();j++){
	    				SA7601 sa = new SA7601();
	    				Row trow = industryDomainList.get(j);
	    				sa.setYear(DateUtil.getCurrentYear(date));
		        		sa.setHalf_year(DateUtil.getHalfYear(date));
		        		sa.setQuarter(DateUtil.getQuarter(date));
		        		sa.setMonth(DateUtil.getCurrentMonth(date));
		        		sa.setWeek(DateUtil.getCurrentWeek(date));
		        		sa.setDay(DateUtil.getCurrentDay(date));
		        		sa.setBuss_type("WEBSITE_RANK_BUSS");
		        		sa.setBuss_value(trow.getAs("parent_industry_type").toString());
		        		sa.setRank(j + 1);
		        		sa.setDomain(trow.getAs("top_domain").toString());
		        	    sa.setWebsite_name(trow.getAs("site_name").toString());
		        	    sa.setIcp_num(trow.getAs("license_key").toString());
		        	    sa.setTraffic(trow.getAs("count").toString());
		        		sa.setSta_range(0);
		        		list_SA7601.add(sa);
	    			}
	    		}
	    	}
	    	industry_tmp_RDD.unpersist();
	    	oper_tmp.unpersist();
	    	
	    	temp_end=System.currentTimeMillis();
            exectime=(temp_end-temp)*1.0/(1000*60);
            temp=temp_end;
			System.out.println("网站分类  exectime: "+exectime+" min........................");
	    	System.out.println("............本省主体....开始............");
	        //分类网站访问量排名 --end
	        String sql_beian = "select a.top_domain,a.count, "
					+ "(CASE WHEN ISNULL(b.license_key) = false THEN B.license_key ELSE 'N/A' END) AS license_key,"
					+ "(CASE WHEN ISNULL(b.site_name) = false THEN B.site_name ELSE 'N/A' END) AS site_name "
					+ "from df_dc_temp a left join br2005_temp b on a.top_domain = b.top_domain where b.LICENSE_KEY like '%"+p_linces_key+"%' order by a.count desc limit 100"; 

	        DataFrame oper_tmp_beian = dataSource.sqlContext().sql(sql_beian);
			List<Row> top_domain_100_beian = oper_tmp_beian.toJavaRDD().collect();
	        if(top_domain_100_beian.size() > 0){
	    		int rank = 1;
	        	for(Row row_top_domain_100_beian : top_domain_100_beian){
	        	    SA7601 sa = new SA7601();
	        		sa.setYear(DateUtil.getCurrentYear(date));
	        		sa.setHalf_year(DateUtil.getHalfYear(date));
	        		sa.setQuarter(DateUtil.getQuarter(date));
	        		sa.setMonth(DateUtil.getCurrentMonth(date));
	        		sa.setWeek(DateUtil.getCurrentWeek(date));
	        		sa.setDay(DateUtil.getCurrentDay(date));
	        		sa.setBuss_type("WEBSITE_RANK_SUM");
	        		sa.setBuss_value("0");
	        		sa.setRank(rank++);
	        		sa.setDomain(row_top_domain_100_beian.getAs("top_domain").toString());
	        	    sa.setWebsite_name(row_top_domain_100_beian.getAs("site_name").toString());
	        	    sa.setIcp_num(row_top_domain_100_beian.getAs("license_key").toString());
	        	    sa.setTraffic(row_top_domain_100_beian.getAs("count").toString());
	        		sa.setSta_range(2); //本省主体是2
	        		list_SA7601.add(sa);
	        	}
	        }
	        
	        df_dc.sqlContext().dropTempTable("df_dc_temp");
	        
	        df_dc.unpersist();
	        temp_end=System.currentTimeMillis();
            exectime=(temp_end-temp)*1.0/(1000*60);
            temp=temp_end;
			System.out.println("本省主体  exectime: "+exectime+" min........................");
	    	
	    	JavaRDD<SA7601> rdd = ctx.parallelize(list_SA7601);
	    	DataFrame df = dataSource.sqlContext().createDataFrame(rdd, SA7601.class);
			outList.add(new OutQueueEntity("SA7601_TEMP", df));
			
			CommonUtils.deleteTaskTableData("SA7601", date, "WEBSITE_RANK_SUM", 0, "day");
			CommonUtils.deleteTaskTableData("SA7601", date, "WEBSITE_RANK_SUM", 2, "day");
			CommonUtils.deleteTaskTableData("SA7601", date, "WEBSITE_RANK_BUSS", 0, "day");
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
		}
		
		long end=System.currentTimeMillis();
		double min=(end-start)*1.0/(1000*60);
		System.out.println("DomainAnalyzTask_SA7601_New:exectime: "+min+" min............");
		return outList;
	}
}
